package com.baidu.fenfayun.demo.act;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;

import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.baidu.yun.gameline.R;
import com.baidu.fenfayun.demo.auth.*;
import com.baidu.fenfayun.demo.home.*;
import com.baidu.fenfayun.demo.base.*;
import com.baidu.fenfayun.demo.model.*;
import com.baidu.fenfayun.demo.util.*;

import android.support.v4.app.Fragment;

public class LoginAct extends BaseFragmentActivity implements SmartLoginCallbacks{
   private static final String TAG = "LoginAct";
   private static final int REQUEST_SIGNUP = 0;

   @BindView(R.id.input_email) EditText _emailText;
   @BindView(R.id.input_password) EditText _passwordText;
   @BindView(R.id.btn_login) QMUIRoundButton _loginButton;
   @BindView(R.id.link_signup) TextView _signupLink;

   SmartUser currentUser;
   SmartLoginConfig config;
   SmartLogin smartLogin;
   QMUITipDialog tipDialog;
   @Override
   protected int getContextViewId() {
      return R.id.loginmain;
   }
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_login);
      ButterKnife.bind(this);
      hideKeyBoard();

      config = new SmartLoginConfig(getApplicationContext(), this);
      _loginButton.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v) {
            login();
         }
      });

      _signupLink.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v) {
            // Start the Signup activity
            Intent intent = new Intent(getApplicationContext(), SignupAct.class);
            startActivityForResult(intent, REQUEST_SIGNUP);

            overridePendingTransition(com.qmuiteam.qmui.R.anim.slide_in_left, com.qmuiteam.qmui.R.anim.slide_out_left);
         }
      });
   }
   public void goHome(){

      BaseFragment fragment = new HomeFragment();
      startFragment(fragment);

   }
   public void login() {
      Log.d(TAG, "Login");

      if (!validate()) {
         onValidateFailed();
         return;
      }

      _loginButton.setEnabled(false);

      tipDialog = new QMUITipDialog.Builder(this)
         .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
         .setTipWord("正在加载")
         .create(); 
      tipDialog.show();
      smartLogin = SmartLoginFactory.build(LoginType.CustomLogin);
      smartLogin.login(config);
   }

   @Override
   public SmartUser doCustomLogin() {
      SmartUser user = new SmartUser();
      String email = _emailText.getText().toString();
      String password = _passwordText.getText().toString();
      UserDB udb = new UserDB();
      UserData one = udb.findOne(email);
      if(one == null){
         //udb.create(email,password,email,"");
         user = null;
      }
      else if(email.equals(one.getEmail()) && password.equals(one.getPassword()))
         user.setEmail(email);
      else user = null;
      return user;
   }

   @Override
   public SmartUser doCustomSignup() {
      SmartUser user = new SmartUser();
      return user;
   }
   @Override
   public void onLoginFailure(SmartLoginException e) {
      _loginButton.setEnabled(true);
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
      tipDialog.dismiss();
      DialogUtil.show(this,"操作失败,帐号不存在或密码错误",DialogUtil.Stype.FAIL);

   }
   @Override
   public void onLoginSuccess(SmartUser user) {
      Toast.makeText(this, user.toString(), Toast.LENGTH_SHORT).show();
      tipDialog.dismiss();
      _loginButton.setEnabled(true);
      goHome();
   }


   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == REQUEST_SIGNUP) {
         if (resultCode == RESULT_OK) {

            // TODO: Implement successful signup logic here
            // By default we just finish the Activity and log them in automatically
            //this.finish();
            goHome();
         }
      }
   }

   @Override
   public void onBackPressed() {
      // Disable going back to the MainActivity
      if (getSupportFragmentManager().getBackStackEntryCount() <= 1 ) {
         moveTaskToBack(true);
      } else {
         super.onBackPressed();
      }
   }

   @Override
   public void onResume()
   {
      super.onResume();
      hideKeyBoard();
   }


   public void onValidateFailed() {
      Toast.makeText(getBaseContext(), "登录失败", Toast.LENGTH_LONG).show();
      _loginButton.setEnabled(true);
   }

   public boolean validate() {
      boolean valid = true;

      String email = _emailText.getText().toString();
      String password = _passwordText.getText().toString();

      if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
         _emailText.setError("请输入有效的邮箱地址");
         valid = false;
      } else {
         _emailText.setError(null);
      }

      if (password.isEmpty() || password.length() < 5 || password.length() > 10) {
         _passwordText.setError("5到10个有效的字符或数字");
         valid = false;
      } else {
         _passwordText.setError(null);
      }

      return valid;
   }
}
